package com.modules.user.service.Impl;

import cn.hutool.core.date.BetweenFormatter;
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.exception.RRException;
import com.common.response.ResponseVO;
import com.common.utils.Query;
import com.common.utils.R;
import com.common.utils.TokenGenerator;
import com.modules.system.entity.Admin;
import com.modules.user.entity.UserEntity;
import com.modules.user.entity.UserEntityVO;
import com.modules.user.mapper.UserMapper;
import com.modules.user.service.IUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements IUserService {

    @Resource
    private UserMapper userMapper;

    /**
     * 登录
     * */
    @Override
    public R doLogin(UserEntity userEntity) {
        String password = SecureUtil.sha1( SecureUtil.md5(userEntity.getPassword()));
        UserEntity userData = this.getOne(new QueryWrapper<UserEntity>().lambda()
                .eq(UserEntity::getUsername, userEntity.getUsername())
                .eq(UserEntity::getPassword, password)
                .ne(UserEntity::getType, 0));
        if (userData == null){
            return R.error("用户不存在");
        }
        // 保存token
        userData.setToken(TokenGenerator.generateValue());
        userMapper.updateById(userData);
        return R.ok().put("data", userData);
    }

    /**
     * 退出
     * */
    @Override
    public R loginOut(UserEntity userEntity) {
        UserEntity userData = this.getOne(new QueryWrapper<UserEntity>().lambda()
                .eq(UserEntity::getUsername, userEntity.getUsername())
                .eq(UserEntity::getPassword, userEntity.getPassword())
                .ne(UserEntity::getType, 0));
        if (userData == null){
            return R.error("用户不存在");
        }

        // 清空token
        userData.setToken(SecureUtil.md5(userData.getId() + userData.getUsername() + SecureUtil.md5(String.valueOf(new Date().getTime()))));
        userMapper.updateById(userData);
        return R.ok();
    }

    /**
     * 修改密码
     * */
    @Override
    public R modifyPass(Map<String, Object> params) {
        String userName = (String) params.get("username");
        String password = (String) params.get("password");
        String newPassword = (String) params.get("newPassword");
        UserEntity userData = this.getOne(new QueryWrapper<UserEntity>().lambda()
                .eq(UserEntity::getUsername, userName)
                .eq(UserEntity::getPassword, SecureUtil.sha1( SecureUtil.md5(password))));
        if (userData == null){
            return R.error("账号密码不正确，请检查重试");
        }

        // 修改
        userData.setPassword(SecureUtil.sha1( SecureUtil.md5(newPassword)));
        userData.setUpdateTime(new Date());
        userMapper.updateById(userData);
        return R.ok();
    }

    @Override
    public R getPageList(Map<String, Object> params) {
        // 根据当前人的token找到用户
        UserEntity userEntity = userMapper.selectOne(new LambdaQueryWrapper<UserEntity>()
            .eq(UserEntity::getToken, params.get("token")));
        if (userEntity == null){
            return R.error("找不到操作人");
        }
        IPage<UserEntityVO> page = new Query<UserEntityVO>().getPage(params);
        List<UserEntityVO> list = userMapper.getPageList(page, userEntity.getId());
        if (!list.isEmpty()){
            Date nowDate = DateUtil.date();
            for (UserEntityVO userEntityVO : list){
                if (userEntityVO.getStatus() == 1){
                    //Level.SECOND表示精确到秒
                    String formatBetween = DateUtil.formatBetween(userEntityVO.getLoginTime(), nowDate, BetweenFormatter.Level.SECOND);
                    userEntityVO.setOnlineTime(formatBetween);
                }
            }
        }
        page.setRecords(list);
        return R.ok().put("data", page);
    }

    @Override
    public R getAgentPageList(Map<String, Object> params) {
        // 根据当前人的token找到用户
        UserEntity userEntity = userMapper.selectOne(new LambdaQueryWrapper<UserEntity>()
                .eq(UserEntity::getId, params.get("userId"))
                .eq(UserEntity::getType, 2));
        if (userEntity == null){
            return R.error("找不到代理商");
        }
        IPage<UserEntityVO> page = new Query<UserEntityVO>().getPage(params);
        List<UserEntityVO> list = userMapper.getPageList(page, userEntity.getId());
        if (!list.isEmpty()){
            Date nowDate = DateUtil.date();
            for (UserEntityVO userEntityVO : list){
                if (userEntityVO.getStatus() == 1){
                    //Level.SECOND表示精确到秒
                    String formatBetween = DateUtil.formatBetween(userEntityVO.getLoginTime(), nowDate, BetweenFormatter.Level.SECOND);
                    userEntityVO.setOnlineTime(formatBetween);
                }
            }
        }
        page.setRecords(list);
        return R.ok().put("data", page);
    }

    @Override
    public UserEntity getUserByLoginName(String username) {
        UserEntity userEntity = this.userMapper.selectOne(new QueryWrapper<UserEntity>().lambda()
        .eq(UserEntity::getUsername, username));

        return userEntity;
    }

    @Override
    public UserEntity getUserByLoginToken(String token) {
        UserEntity userEntity = this.userMapper.selectOne(new QueryWrapper<UserEntity>().lambda()
                .eq(UserEntity::getToken, token));

        return userEntity;
    }
}
